<?php

use yii\db\Schema;
use yii\db\Migration;

class m160704_095204_update_creative_size_list_field extends Migration
{
    public function up()
    {
        $sql = "select id, width, height from {{%creative}}";
        $db = \Yii::$app->db;
        $cmd = $db->createCommand($sql);
        $creatives = $cmd->queryAll();
        $update = "update {{%creative}} set width = substring_index(width, ',', 1);";
        $this->execute($update);
        $update = "update {{%creative}} set height = substring_index(height, ',', 1);";
        $this->execute($update);
        $this->alterColumn('{{%creative}}', 'width', 'int not null default 0 comment "primary width"');
        $this->alterColumn('{{%creative}}', 'height', 'int not null default 0 comment "primary height"');
        $updateSql = '';
        foreach ($creatives as $creative) {
            $id = $creative['id'];
            $primaryWidth = (int) $creative['width'];
            $primaryHeight = (int) $creative['height'];
            $widths = explode(',', $creative['width']);
            $heights = explode(',', $creative['height']); 
            $list = [];
            foreach($widths as $k => $width) {
                $list[] = $width.'*'.$heights[$k];
            }
            $sizeList = implode(',', $list);
            $updateSql .= "update {{%creative}} set width='$primaryWidth', height='$primaryHeight', size_list='$sizeList' where id = $id;";
        } 
        if ($updateSql) return $this->execute($updateSql);
        return true;
    }

    public function down()
    {
        return true;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}
